package com.thinkwide.data.spring.config;

import com.thinkwide.data.ormapping.banner.PrintedBanner;
import com.thinkwide.data.ormapping.db.MFConnectionInfo;
import com.thinkwide.data.ormapping.db.MFConnectionPool;
import com.thinkwide.data.ormapping.db.MFDbType;
import com.thinkwide.data.util.DbUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.Objects;

/**
 * 数据源
 *
 * @author andyzhang
 * @since 2023/04/27
 */
@Component
public class DataSourceAutoConfiguration implements InitializingBean, ApplicationContextAware {
    private static Logger logger = LoggerFactory.getLogger(DataSourceAutoConfiguration.class);
    @Autowired
    private DataSourceProperties dataSourceProperties;

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        try {
            MFConnectionPool.getInstance().setPropLoad(false);
            DataSource ds = applicationContext.getBean(DataSource.class);
            if (Objects.nonNull(ds)) {
                MFConnectionInfo connectionInfo = new MFConnectionInfo();
                MFDbType dbType = DbUtils.getDataBaseType(dataSourceProperties.determineDriverClassName());
                //logger.info(JsonUtils.objectToJson(dataSourceProperties));
                //logger.info(dbType.name());
                connectionInfo.setDbType(dbType.name());
                connectionInfo.setAdapterClasses(DbUtils.getAdapterClasses(dbType));
                //logger.info(DbUtils.getAdapterClasses(dbType));
                connectionInfo.setName(MFConnectionPool.DEFAULT);
                connectionInfo.setActiveDataSource(ds);
                MFConnectionPool.getInstance().createConnectionDynamicDataSource(connectionInfo);
                MFConnectionPool.getInstance().changeDefConnection(connectionInfo.getName());
            }

            PrintedBanner banner = new PrintedBanner();
            banner.printBanner(System.out);

        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
        }
    }
}
